<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Models\Category;
use Illuminate\Http\Request;

class CategoryController extends BaseController
{
    /**
     * 分类列表
     */
    public function index(Request $request)
    {
        $type = $request->input('type');
        if($type === 'all'){
//            包含禁用的分类
            return cache_category_all();
        }else{
//            不包含禁用的分类
            return cache_category();
        }
    }

    /**
     * 添加分类  最大三级分类
     */
    public function store(Request $request)
    {
        $insertData = $this->checkInput($request);
        if(!is_array($insertData)) return $insertData;

        Category::create($insertData);

        return $this->response->created();
    }

    /**
     * 分类详情
     */
    public function show(Category $category)
    {
        return $category;
    }

    /**
     * 更新分类
     */
    public function update(Request $request, Category $category)
    {
        $uploadData = $this->checkInput($request);
        if(!is_array($uploadData)) return $uploadData;

        Category::updated($uploadData);

        return $this->response->noContent();
    }

    /**
     * 检查验证输入得数据
     */
    protected function checkInput($request)
    {
//        验证参数
        $request->validate([
            'name' => 'required|max:16'
        ],[
            'name.required' => '分类名称不能为空'
        ]);

//        获取分组
        $group = $request->input('group','goods');

//        批量赋值, 不能直接添加, 需要通过 pid 计算等级 level
        $pid = $request->input('pid',0);
        $level = $pid == 0 ? 1 : (Category::find($pid)->level + 1);

        if($level > 3) {
            return $this->response->errorBadRequest('最大为三级分类');
        }

        return [
            'name' => $request->input('name'),
            'pid' => $pid,
            'level' => $level,
            'group' => $group,
        ];
    }

    /**
     * 分类状态
     */

    public function status(Category $category)
    {
        $category->status = $category->status == 0 ? 1 : 0;
        $category->save();

        return $this->response->noContent();
    }
}
